package gui.applets;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class AppletText extends Applet{
	Button btn1=new Button("Get Text");
	Button btn2=new Button("Set Text");
	TextField tf1=new TextField(30);
	TextField tf2=new TextField(30);
	TextField tf3=new TextField(30);
	
	String s=new String();
	
	public void init(){
		this.btn1.addActionListener(new Btn1());
		this.btn2.addActionListener(new Btn2());
		this.tf1.addTextListener(new TF());
		this.tf1.addActionListener(new TA());
		this.tf1.addKeyListener(new TK());
		
		this.add(this.btn1);
		this.add(this.btn2);
		this.add(this.tf1);
		this.add(this.tf2);
		this.add(this.tf3);
	}
	
	class TF implements TextListener{

		@Override
		public void textValueChanged(TextEvent e) {
			tf2.setText(tf1.getText());
			
		}
		
	}
	
	class TA  implements ActionListener{

		private int count=0;
		@Override
		public void actionPerformed(ActionEvent e) {
			tf3.setText("Tf1 Action Event "+count++);
		}
		
	}
	
	class TK extends KeyAdapter{
		public void keyTyped(KeyEvent e){
			String ts=tf1.getText();
			if(e.getKeyChar()==KeyEvent.VK_BACK_SPACE){
				if(ts.length()>0){
					ts=ts.substring(0,ts.length()-1);
					tf1.setText(ts);
				}
			}else
				tf1.setText(tf1.getText()+Character.toUpperCase(e.getKeyChar()));
			
			tf1.setCaretPosition(tf1.getText().length());
			e.consume();
		}
	}
	
	class Btn1 implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			s=tf1.getSelectedText();
			if(s.length()==0)s=tf1.getText();
			tf1.setEditable(false);
		}
		
	}
	
	class Btn2  implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			tf1.setText("Insert by Button 2:"+s);
			tf1.setEditable(false);
		}
		
	}
	
	public static void main(String[] args){
		AppletText at=new AppletText();
		Frame frame=new Frame("AppletText");
		frame.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
		frame.add(at,BorderLayout.CENTER);
		frame.setSize(300,200);
		at.init();
		at.start();
		frame.setVisible(true);
	}
	
}
